﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domaine;
using Repository;
using Ninject;
using System.ServiceModel.Activation;
using Persistance.ViewModel;
using System.Configuration;

namespace Persistance
{
    public class GestionCompte : IGestionCompte
    {
        [Inject]
        public IUnitOfWork UnitOfWork { get; set; }

        /// <summary>
        /// s'authentifier dans ExaPlanning
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool LogIn(string login, string password)
        {
            using (UnitOfWork = new UnitOfWork())
            {
                return UnitOfWork.CollaboratorRepository.Exists(c => c.Login == login && c.Password == password && c.IsActive==true);
            }
        }

        /// <summary>
        /// renvoie la vue du collaborateur loggué
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public CollaboratorViewModel getCollabLoggedIn(string login)
        {
            Collaborator collabLoggedIn = UnitOfWork.CollaboratorRepository.Single(c => c.Login == login);

            CollaboratorViewModel collab = new CollaboratorViewModel();
            collab.Email = collabLoggedIn.Email;
            collab.FirstName = collabLoggedIn.FirstName;
            collab.Job = collabLoggedIn.Job.Name;
            collab.Location = collabLoggedIn.Location.Name;
            collab.Login = collabLoggedIn.Login;
            collab.MobilePhone = collabLoggedIn.MobilePhone;
            collab.Name = collabLoggedIn.Name;
            collab.ImageInfo = new ImageInfoViewModel { URLImage = collabLoggedIn.URLImage, LastModification = collabLoggedIn.ModificationDate };
            collab.JobID = collabLoggedIn.Job.ID;
            collab.LocationID = collabLoggedIn.Location.ID;
            collab.ActivityID = collabLoggedIn.Activity.ID;
            collab.IsActive = collabLoggedIn.IsActive;
            return collab;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<LocationViewModel> GetAllLocation()
        {
            return UnitOfWork.LocationRepository.All().Select((l) => new LocationViewModel { Name = l.Name, ID = l.ID }).ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<JobViewModel> GetAllJob()
        {
            return UnitOfWork.JobRepository.All().Select((j) => new JobViewModel { Name = j.Name, ID = j.ID }).ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<ActivityViewModel> GetAllActivity()
        {
            return UnitOfWork.ActivityRepository.All().Select((a) => new ActivityViewModel { Name = a.Name, ID = a.ID }).ToList();
        }
        /// <summary>
        /// Permets a un RA d'ajouter un nouveau collaborateur
        /// </summary>
        /// <param name="login"></param>
        /// <param name="loginNewCollab"></param>
        /// <param name="passwordNewCollab"></param>
        /// <param name="name"></param>
        /// <param name="firstName"></param>
        /// <param name="mobilePhone"></param>
        /// <param name="email"></param>
        /// <param name="job"></param>
        /// <param name="location"></param>
        /// <param name="activity"></param>
        public void Register(String login, string loginNewCollab, string passwordNewCollab, string name, string firstName, string mobilePhone, string email, int job, int location, int activity)
        {
            var collab = UnitOfWork.CollaboratorRepository.Single(c => c.Login == login);
            //verification des droits de l'utilisateur
            if (collab.Job.ID != (int)JobEnum.RA)
            {
                throw new Exception("Vous n'avez pas les droits necessaires.");
            }
            
            //verification de la disponibilite du loginNewCollab
            if (UnitOfWork.CollaboratorRepository.Exists(c => c.Login == loginNewCollab))
            {
                throw new Exception("Il existe déjà un collaborateur ayant comme login " + loginNewCollab + ".");
            }
            //verification de l'unicité de l'adresse mail
            if (UnitOfWork.CollaboratorRepository.Exists(c => c.Email == email))
            {
                throw new Exception("Il existe déjà un collaborateur ayant comme e-mail " + email + ".");
            }
            //verification de la structure de l'adresse mail 
            if (!Utils.ValidMail(email))
            {
                throw new Exception("L'adresse " + email + " n'est pas un e-mail valide."); 
            }
            //verification de la structure du numero de tel
            if (mobilePhone != "" && !Utils.ValidMobilePhone(mobilePhone))
            {
                throw new Exception("Le numéro de téléphone " + mobilePhone + " n'est pas valide.");
            }

            Collaborator newCollab = new Collaborator();
            newCollab.Login = loginNewCollab;
            newCollab.Password = passwordNewCollab; //peut etre une encription ici ou avant de le mettre en paramètre...
            newCollab.Name = name;
            newCollab.FirstName = firstName;
            newCollab.Email = email;
            newCollab.MobilePhone = mobilePhone;
            newCollab.Activity = UnitOfWork.ActivityRepository.Single(a => a.ID == activity);
            newCollab.Job = UnitOfWork.JobRepository.Single(j => j.ID == job);
            newCollab.Location = UnitOfWork.LocationRepository.Single(l => l.ID == location);
            newCollab.ModificationDate = DateTime.Now;
            newCollab.URLImage = String.Empty;

            UnitOfWork.Save();
            
        }

        /// <summary>
        /// Permet a la personne logguee de modifier ces informations
        /// </summary>
        /// <param name="login"></param>
        /// <param name="newPassword"></param>
        /// <param name="name"></param>
        /// <param name="firstName"></param>
        /// <param name="mobilePhone"></param>
        /// <param name="email"></param>
        /// <param name="image"></param>
        public void EditProfile(String login, string newPassword, string name, string firstName, string mobilePhone, string email, byte[] image)
        {

            Collaborator collabLoggedIn = UnitOfWork.CollaboratorRepository.Single(c => c.Login == login);

            //verification de la structure de l'adresse mail 
            if (! Utils.ValidMail(email))
            {
                throw new Exception("L'adresse " + email + " n'est pas un e-mail valide.");
            }

            
            //verification de la structure du numero de tel
            if (mobilePhone != "" && !Utils.ValidMobilePhone(mobilePhone))
            {
                throw new Exception("Le numéro de téléphone " + mobilePhone + " n'est pas valide.");
            }

            collabLoggedIn.Password = newPassword; //peut etre une encription ici ou avant de le mettre en paramètre...
            collabLoggedIn.Name = name;
            collabLoggedIn.FirstName = firstName;
            collabLoggedIn.Email = email;
            collabLoggedIn.MobilePhone = mobilePhone;
            collabLoggedIn.ModificationDate = DateTime.Now;
            Utils.SaveImage(image, collabLoggedIn.Login, ConfigurationManager.AppSettings["ImageContainer"], collabLoggedIn.ModificationDate);//"images"

            UnitOfWork.Save();
        }

        /// <summary>
        /// Permet a un RA de modifier la fonction, l'activite et la localisation d'un de ses collaborateurs
        /// </summary>
        /// <param name="login"></param>
        /// <param name="loginCollab"></param>
        /// <param name="job"></param>
        /// <param name="activity"></param>
        /// <param name="location"></param>
        public void EditCollab(String login, string loginCollab, int job, int activity, int location)
        {
            Collaborator collab, collabToEdit;

            collab = UnitOfWork.CollaboratorRepository.Single(c => c.Login == login);

            //verification des droits de l'utilisateur
            if (collab.Job.ID != (int)JobEnum.RA)
            {
                throw new Exception("Vous n'avez pas les droits necessaires.");
            }

            //verification loginCollab
            if (!UnitOfWork.CollaboratorRepository.Exists(c => c.Login == loginCollab && c.IsActive))
            {
                throw new Exception("Le collaborateur " + loginCollab + " n'existe pas.");
            }
            collabToEdit = UnitOfWork.CollaboratorRepository.Single(c => c.Login == loginCollab);
            //verification loginCollab associé a login
            if (!Utils.CollabAssociateToRA(collab, collabToEdit))
            {
                throw new Exception("Vous n'avez pas les droits necessaires.");
            }

            collabToEdit.Activity = UnitOfWork.ActivityRepository.Single(a => a.ID == activity);
            collabToEdit.Job = UnitOfWork.JobRepository.Single(j => j.ID == job);
            collabToEdit.Location = UnitOfWork.LocationRepository.Single(l => l.ID == location);
            
            UnitOfWork.Save();
        }

        /// <summary>
        /// Rend inactif le collaborateur passé en paramètre
        /// </summary>
        /// <param name="login"></param>
        /// <param name="loginCollab"></param>
        public void DeleteCollab(string login, string loginCollab)
        {
            Collaborator collab, collabToRemove;

            collab = UnitOfWork.CollaboratorRepository.Single(c => c.Login == login);


            //verification des droits de l'utilisateur
            if (collab.Job.ID != (int)JobEnum.RA)
            {
                throw new Exception("Vous n'avez pas les droits necessaires.");
            }

            //verification du loginCollab
            if (!UnitOfWork.CollaboratorRepository.Exists(c => c.Login == loginCollab && c.IsActive))
            {
                throw new Exception("Le collaborateur " + loginCollab + " n'existe pas.");
            }

            collabToRemove= UnitOfWork.CollaboratorRepository.Single(c => c.Login == loginCollab);
            if (!Utils.CollabAssociateToRA(collab,collabToRemove))
            {
                throw new Exception("Vous n'avez pas les droits necessaires.");
            }
            collabToRemove.IsActive = false;

            UnitOfWork.Save();
        }
    }

}
